<html>
<head>
    <style>
        .bold {
            font-weight: bold;
        }
    </style>
</head>

<body class="selection-disabled">

<p>
    This is the text and <span class="bold">this is the bold part via CSS</span> and this is a <b>b element</b>.
</p>

<textarea id="output">

</textarea>

<script type="module">

    function createSyntheticSelection(start, end) {

        let selection = window.getSelection();

        selection.empty();

        let range = document.createRange();

        range.setStart(start.node, start.offset);


        range.setEnd(end.node, end.offset);

        selection.addRange(range);

        return selection;

    }

    function toHTML(range) {

        let result = "";

        let docFragment = range.cloneContents();

        docFragment.childNodes.forEach(childNode => {

            if(childNode.nodeType === Node.TEXT_NODE) {
                result += childNode.textContent;
            } else {
                console.log("this is an alement");
                result += (childNode).outerHTML;
            }

        });

    return result;

    }

    createSyntheticSelection({ node: document.querySelector("p"), offset: 0},
                             { node:  document.querySelector("p"), offset: 4});

    let sel = window.getSelection();

    let range = sel.getRangeAt(0);

    let html = toHTML(range);

    console.log("setting textarea to" + html)

    document.querySelector('textarea').content = 'asdf' +  html;

</script>


</body>
</html>
